package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.FriendList;
import com.example.entity.User;
import com.example.mapper.FriendListMapper;
import com.example.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 好友列表业务处理
 **/
@Service
public class FriendListService {

    @Resource
    private FriendListMapper friendListMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * 新增
     */
    public void add(FriendList friendList) {
        friendListMapper.insert(friendList);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        friendListMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            friendListMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(FriendList friendList) {
        friendListMapper.updateById(friendList);
    }

    /**
     * 根据ID查询
     */
    public FriendList selectById(Integer id) {
        return friendListMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<FriendList> selectAll(FriendList friendList) {
        List<FriendList> list = friendListMapper.selectAll(friendList);
        for (FriendList friendList1 : list) {
            User user = userMapper.selectById(friendList1.getFriendId());
            if (ObjectUtil.isNotEmpty(user)) {
                friendList1.setFriendName(user.getName());
                friendList1.setFriendAvatar(user.getAvatar());
                friendList1.setFriendUserName(user.getUsername());
            }
        }
        return list;
    }

    /**
     * 分页查询
     */
    public PageInfo<FriendList> selectPage(FriendList friendList, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<FriendList> list = this.selectAll(friendList);
        return PageInfo.of(list);
    }

    @Transactional
    public void showPk(Integer userId, Integer friendId) {
        FriendList friendList = new FriendList();
        friendList.setFriendId(friendId);
        friendList.setUserId(userId);
        friendList.setIsShowPublicKey(1);
        friendListMapper.showPk(friendList);
    }
}